package com.caxxb.controller;

import cn.hutool.crypto.SecureUtil;
import com.caxxb.common.R;
import com.caxxb.entity.User;
import com.caxxb.service.LogService;
import com.caxxb.service.UserService;
import com.caxxb.service.impl.LogServiceImpl;
import com.caxxb.service.impl.UserServiceImpl;
import com.caxxb.util.PageData;
import com.caxxb.util.QueryResponseData;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;


@RestController
@RequestMapping("/user")
@CrossOrigin("*")
public class UserController {

    private UserService userService=new UserServiceImpl();

    //查询功能
    @GetMapping("/query")
    public QueryResponseData getNumByPage(@RequestParam(name = "page", required = false, defaultValue = "1") int pageNo, @RequestParam(name = "limit", required = false, defaultValue = "10") int pageSize, @RequestParam(name = "num", required = false, defaultValue = "%%") String num) {

        PageData pageData = userService.getNumByPage(num, pageNo, pageSize);

        QueryResponseData<User> queryResponseData = new QueryResponseData<>();
        //数量
        queryResponseData.setCount(pageData.getTotal());
        queryResponseData.setData(pageData.getData());

        return queryResponseData;
    }




    private LogService logService=new LogServiceImpl();


    @PostMapping("add")
    public R<Boolean> add(@RequestBody User user){
        System.out.println(user);
        boolean flag = userService.addUser(user);
        if(flag == false){
            return R.error("注册失败");
        }else {
            return R.success(flag);
        }
    }

    //登录功能
    @PostMapping("/login")
    public R<User> login(@RequestBody User user,HttpServletRequest request){
//        log.info(map.toString());
        //得到输入的账户密码
        String account_number=user.getAccount_number();
        //对密码进行加密处理
        String password = user.getPassword();
        String md5password = SecureUtil.md5(password);

//        System.out.println("加密后密码"+md5password);

        List<User> login = userService.login(account_number,md5password);

        System.out.println(login);
        //登录失败返回错误信息
        if (login.size()==0){
            return R.error("登录失败");
        }

        //获取登录用户对象
        User loginuser = login.get(0);
        //得到用户id
        int userid = loginuser.getUser_id();

        //在session中存放用户id
        request.getSession().setAttribute("user",userid);
        System.out.println("用户已登录");

        String ip = getIpAddr(request);

        LocalDateTime now = LocalDateTime.now();
//        String time = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        logService.recordLog(userid,ip,now);
       /* System.out.println("ip:"+ip);
        System.out.println("userid:"+userid);
        System.out.println("time:"+time);*/

        return R.success(user);
    }

    //登出功能
    @PostMapping("/loginout")
    private R<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return R.success("退出成功");
    }

    //展示用户信息
    @GetMapping("/showaccount")
    private R show2User(HttpSession session){
        int userid = (int) session.getAttribute("user");
        List<User> userList = userService.getUserById(userid);
        User user = userList.get(0);
        return R.success(user);
    }

    //修改邮箱
    @PutMapping("updateemail/{email}")
    private R updateEamil(@PathVariable String email,HttpSession session){
        int userid = (int) session.getAttribute("user");
//        System.out.println("email="+email);
        boolean flag = userService.UpdateUserEmail(email, userid);
        if(flag){
            return R.success("修改成功");
        }else {
            return R.error("修改失败");
        }

    }

    //检查密码是否一致
    @GetMapping("checkpwd/{password}")
    private R checkPassword(@PathVariable String password,HttpSession session){
        int userid = (int) session.getAttribute("user");
        List<User> userlist = userService.getUserById(userid);
        User user = userlist.get(0);
        String originalpwd = user.getPassword();

        System.out.println("password:"+password);
        String md5pwd = SecureUtil.md5(password);

        if (originalpwd.equals(md5pwd)){
            System.out.println("密码一致");
            return R.success(md5pwd);
        }else {
            return R.error("原密码不一致");
        }
    }

    //修改密码
    @PutMapping("updatepwd/{password}")
    public R updatePwd(@PathVariable String password,HttpSession session){
        int userid = (int) session.getAttribute("user");


        System.out.println("password:"+password);
        String md5pwd = SecureUtil.md5(password);

        boolean flag = userService.UpdateUserPwd(md5pwd, userid);

        if(flag){
            //修改成功移除用户
            session.removeAttribute("user");
            return R.success(flag);
        }else {
            return R.error("修改失败");
        }
    }

    /**
     * 删除用户
     * @param user_id
     * @return
     */
    @PutMapping("/del/{user_id}")
    public R<Boolean> del(@PathVariable int user_id){
        boolean flag = userService.delUser(user_id);
        return R.success(flag);
    }

    /**
     * 修改用户
     * @param user_id
     * @param user
     * @return
     */
    @PutMapping("/update/{user_id}")
    public R<Boolean> update(@PathVariable int user_id,@RequestBody User user){
        System.out.println("userid:"+user_id);
        boolean flag = userService.updateUser(user_id,user);
        return R.success(flag);
    }


    public  String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        if (ip.split(",").length > 1) {
            ip = ip.split(",")[0];
        }
        return ip;
    }
}
